<template>
  <view class="edit-profile-container">
    <u-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px">
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <u-form-item label="用户名" prop="username">
          <u-input 
            v-model="userForm.username" 
            placeholder="请输入用户名"
            :disabled="true"
          />
        </u-form-item>
        
        <u-form-item label="真实姓名" prop="realName">
          <u-input 
            v-model="userForm.realName" 
            placeholder="请输入真实姓名"
          />
        </u-form-item>
        
        <u-form-item label="昵称" prop="nickname">
          <u-input 
            v-model="userForm.nickname" 
            placeholder="请输入昵称"
          />
        </u-form-item>
        
        <u-form-item label="手机号" prop="phone">
          <u-input 
            v-model="userForm.phone" 
            placeholder="请输入手机号"
            type="number"
          />
        </u-form-item>
        
        <u-form-item label="邮箱" prop="email">
          <u-input 
            v-model="userForm.email" 
            placeholder="请输入邮箱"
            type="email"
          />
        </u-form-item>
      </view>
      
      <view class="form-section">
        <view class="section-title">头像设置</view>
        
        <view class="avatar-section">
          <view class="avatar-preview">
            <image 
              :src="userForm.avatar || '/static/images/default-avatar.png'" 
              class="avatar-image"
              @click="chooseAvatar"
            />
            <view class="avatar-edit-icon">
              <u-icon name="camera" color="#fff" size="16" />
            </view>
          </view>
          <text class="avatar-tip">点击头像更换</text>
        </view>
      </view>
      
      <view class="form-section">
        <view class="section-title">其他信息</view>
        
        <u-form-item label="个人简介" prop="bio">
          <u-textarea 
            v-model="userForm.bio" 
            placeholder="请输入个人简介"
            :maxlength="200"
            show-count
          />
        </u-form-item>
        
        <u-form-item label="地址" prop="address">
          <u-input 
            v-model="userForm.address" 
            placeholder="请输入详细地址"
          />
        </u-form-item>
      </view>
    </u-form>
    
    <view class="form-actions">
      <u-button 
        type="primary" 
        @click="saveProfile"
        :loading="saving"
        :disabled="saving"
      >
        保存修改
      </u-button>
      
      <u-button 
        type="default" 
        @click="resetForm"
        :disabled="saving"
      >
        重置
      </u-button>
    </view>
    
    <!-- 权限提示组件 -->
    <permission-tip ref="permissionTip" />
  </view>
</template>

<script>
/**
 * 用户信息编辑页面
 * @author Wu.Liang
 * @date 2025-01-27
 */

import { ref, reactive, onMounted } from 'vue'
import { useUserStore, useAuthStore } from '@/store'
import PermissionTip from '@/components/PermissionTip.vue'

export default {
  name: 'EditProfile',
  components: {
    PermissionTip
  },
  setup() {
    const userStore = useUserStore()
    const authStore = useAuthStore()
    
    // 表单引用
    const userFormRef = ref(null)
    
    // 响应式数据
    const userForm = reactive({
      username: undefined,
      realName: undefined,
      nickname: undefined,
      phone: undefined,
      email: undefined,
      avatar: undefined
    })
    
    const saving = ref(false)
    
    // 表单验证规则
    const userRules = {
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2-20个字符', trigger: 'blur' }
      ],
      phone: [
        { 
          validator: (rule, value, callback) => {
            if (!value) {
              callback()
              return
            }
            // 如果是脱敏数据（包含*号），则跳过格式校验
            if (value.includes('*')) {
              callback()
              return
            }
            // 否则进行格式校验
            const pattern = /^1[3-9]\d{9}$/
            if (!pattern.test(value)) {
              callback(new Error('请输入正确的手机号'))
              return
            }
            callback()
          }, 
          trigger: 'blur' 
        }
      ],
      email: [
        { 
          validator: (rule, value, callback) => {
            if (!value) {
              callback()
              return
            }
            // 如果是脱敏数据（包含*号），则跳过格式校验
            if (value.includes('*')) {
              callback()
              return
            }
            // 否则进行格式校验
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
            if (!emailPattern.test(value)) {
              callback(new Error('请输入正确的邮箱格式'))
              return
            }
            callback()
          }, 
          trigger: 'blur' 
        }
      ]
    }
    
    // 页面生命周期
    onMounted(() => {
      loadUserInfo()
    })
    
    // 方法
    const loadUserInfo = () => {
      const userInfo = authStore.userInfo
      if (userInfo) {
        Object.assign(userForm, {
          username: userInfo.username || undefined,
          realName: userInfo.realName || undefined,
          nickname: userInfo.nickname || undefined,
          phone: userInfo.phone || undefined,
          email: userInfo.email || undefined,
          avatar: userInfo.avatar || undefined
        })
      }
    }
    
    const chooseAvatar = () => {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          uploadAvatar(tempFilePath)
        },
        fail: (error) => {
          console.error('选择头像失败:', error)
          uni.showToast({
            title: '选择头像失败',
            icon: 'none'
          })
        }
      })
    }
    
    const uploadAvatar = async (filePath) => {
      try {
        uni.showLoading({ title: '上传中...' })
        
        const result = await uni.uploadFile({
          url: '/api/user/upload-avatar',
          filePath: filePath,
          name: 'avatar',
          header: {
            'Authorization': `Bearer ${authStore.token}`
          }
        })
        
        const response = JSON.parse(result.data)
        if (response.code === 200) {
          userForm.avatar = response.data.url
          uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          })
        } else {
          throw new Error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('头像上传失败:', error)
        uni.showToast({
          title: '头像上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
    
    const saveProfile = async () => {
      try {
        // 表单验证
        const valid = await userFormRef.value.validate()
        if (!valid) {
          return
        }
        
        saving.value = true
        
        // 处理提交数据，过滤掉脱敏字段
        const submitData = {}
        
        if (userForm.realName && !userForm.realName.includes('*')) {
          submitData.realName = userForm.realName
        }
        // 昵称字段：允许空字符串，但过滤脱敏数据
        if (userForm.nickname !== undefined && !userForm.nickname.includes('*')) {
          submitData.nickname = userForm.nickname
        }
        if (userForm.phone && !userForm.phone.includes('*')) {
          submitData.phone = userForm.phone
        }
        if (userForm.email && !userForm.email.includes('*')) {
          submitData.email = userForm.email
        }
        if (userForm.avatar && !userForm.avatar.includes('*')) {
          submitData.avatar = userForm.avatar
        }
        
        // 调用移动端专用API保存用户信息
        const result = await userStore.updateUserProfile(submitData)
        
        if (result) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        console.error('保存用户信息失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        saving.value = false
      }
    }
    
    const resetForm = () => {
      loadUserInfo()
      userFormRef.value.resetFields()
    }
    
    return {
      userForm,
      userRules,
      saving,
      chooseAvatar,
      saveProfile,
      resetForm,
      userFormRef
    }
  }
}
</script>

<style scoped>
.edit-profile-container {
  padding: 16px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.avatar-preview {
  position: relative;
  margin-bottom: 12px;
}

.avatar-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-edit-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 24px;
  height: 24px;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #fff;
}

.avatar-tip {
  font-size: 12px;
  color: #999;
}

.form-actions {
  display: flex;
  gap: 12px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  margin-top: 16px;
}

.form-actions .u-button {
  flex: 1;
}
</style> 